package com.fancon.android.gardenjokesx.activity;

import java.io.IOException;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.FlickrLibrary;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;

public class S03_3Activity extends GardenJokesBaseActivity {
	private WebView webView;
	private RelativeLayout	topBar;
	public static final String CALLBACK_URL = "meshtiles://";
	
	private FlickrLibrary flickrLib;
	private int screenID;
	private String isSignIn;
	
	private Bundle bund;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.s03_1_2_3_4_7);
		
		if(getIntent().getExtras() != null){
			bund = getIntent().getExtras();
			screenID = bund.getInt(Constant.SCREEN_ID);
			isSignIn = getIntent().getExtras().getString(Constant.IS_SIGNIN);
		}
		
	    CookieSyncManager.createInstance(this); 
	    CookieManager cookieManager = CookieManager.getInstance();
	    cookieManager.removeAllCookie();

		webView = (WebView) findViewById(R.id.s03_12347_webview);

//		set Backgroud cho Top Bar
		topBar = (RelativeLayout) findViewById(R.id.s03_12347_bg_top);
		topBar.setVisibility(View.GONE);

		flickrLib = new FlickrLibrary(getApplicationContext());

		setUpWebView(flickrLib.redirectAuthPage("write"));
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode==KeyEvent.KEYCODE_BACK) {
            bund.putBoolean(Constant.LINK_STATE, false);
	    	finishAc();
	    }
	    return(super.onKeyDown(keyCode, event));
	}
	
	private void setUpWebView(String url) {
		webView.setVerticalScrollBarEnabled(false);
		webView.setHorizontalScrollBarEnabled(false);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setAppCacheEnabled(false);
		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		webView.getSettings().setSavePassword(false);
		webView.setWebViewClient(new MyWebViewClient());
		webView.loadUrl(url);
		webView.requestFocus();
	}

	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.v("URLLoader", url);
			if (url.startsWith(CALLBACK_URL)) {
				try {
					if (flickrLib.getToken(flickrLib.getFrob(url))) {
						User userID = new User();
						userID = UserUtil.getInfoUserLogin(S03_3Activity.this);

						DatabaseHelper db = new DatabaseHelper(getApplicationContext());
						db.addFlickrUser(userID.getUser_id(), flickrLib.flickrId, flickrLib.token, flickrLib.userName);
						db.close();
			            bund.putBoolean(Constant.LINK_STATE, true);
						Log.v("Save Database", flickrLib.flickrId + "; " + flickrLib.token + "; " + flickrLib.userName );
					} else {
			            bund.putBoolean(Constant.LINK_STATE, false);
						Toast.makeText(view.getContext(), "Can not authentification. Try again.", Toast.LENGTH_LONG).show();
					}
					
					finishAc();
				} catch (IOException e) {
					Toast.makeText(view.getContext(), "Can not connect flickr.Check your Internet connection.", Toast.LENGTH_LONG).show();
		            bund.putBoolean(Constant.LINK_STATE, false);
					finishAc();
				}

			} else {
				view.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Log.v("Page error", description);
			super.onReceivedError(view, errorCode, description, failingUrl);
		}
		
        @Override
        public void onPageFinished(WebView view, String url) {
        	ClearCacheWebview();
        }
	}

	public void ClearCacheWebview(){
   	  	S03_3Activity.this.deleteDatabase("webview.db");
   	  	S03_3Activity.this.deleteDatabase("webviewCache.db");
    	webView.clearHistory();
		webView.clearFormData();
		webView.clearCache(true);
		Log.v("Clear cache webview", "Clear success");
	}

	public void finishAc() {
		ClearCacheWebview();
		
		switch (screenID) {
		case Constant.S03:
			//@binhbt comment
			Intent ii = new Intent(S03_3Activity.this.getApplicationContext(), S03Activity.class);
			ii.putExtra(Constant.IS_SIGNIN, isSignIn);
			startActivity(ii);
			finish();
			
			break;
		
		case Constant.M01_1:
			Intent inten = getIntent();
			inten.putExtras(bund);
			setResult(RESULT_OK,inten);
			finish();
			break;
		
		case Constant.P06:
			Intent in = getIntent();
			in.putExtras(bund);
			setResult(RESULT_OK, in);
			finish();
			break;
			
		case Constant.M04_7:
			Intent intent = getIntent();
			intent.putExtras(bund);
			setResult(RESULT_OK,intent);
			finish();
			break;
			
		case Constant.S07:
			//@binhbt comment
			/*
			Intent inn = new Intent(S03_3Activity.this, S07Activity.class);
			inn.putExtras(bund);
			startActivity(inn);
			finish();
			*/
			
			break;
			
		default:
			finish();
			break;
		}
	}
}
